package com.paas.form.controller;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.bpm.feign.model.ProcessCmd;
import com.bpm.feign.service.IBpmProcessInstanceService;
import com.paas.common.jdbc.JdbcSql;
import com.paas.common.jdbc.model.DbConfig;
import com.paas.common.jdbc.model.DbTypeEnum;
import com.paas.common.model.BaseUserInfo;
import com.paas.common.model.DataBaseEntity;
import com.paas.common.model.RestResponse;
import com.paas.common.util.BeanUtil;
import com.paas.common.util.StringUtil;
import com.paas.common.web.SystemConst;
import com.paas.common.web.annotion.OperLog;
import com.paas.common.web.controller.BaseController;
import com.paas.common.web.oper.OprLogConstant;
import com.paas.form.dto.FormMasterApplyBPMDTO;
import com.paas.form.dto.FormMasterApplyDTO;
import com.paas.form.entity.FormAttributePubEntity;
import com.paas.form.entity.FormMasterApplyEntity;
import com.paas.form.entity.FormViewPubEntity;
import com.paas.form.service.IFormAttributePubService;
import com.paas.form.service.IFormMasterApplyService;
import com.paas.form.service.IFormViewPubService;
import com.paas.form.service.impl.ApplyHandler;
import com.paas.form.vo.ConditionItem;
import com.paas.form.vo.ConditionVo;
import com.paas.plus.tool.realTimeDistributed.model.RealTimeDistributeConfig;
import com.paas.plus.tool.realTimeDistributed.server.IRealTimeDistributeServer;
import com.paas.tool.feign.service.IMdmToolsRealtimeDistributionService;
import com.publics.entity.UcUserEntity;
import com.publics.feign.service.IAttachmentInstService;
import com.publics.feign.service.IUcDataBaseService;
import com.publics.feign.service.IUcUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import java.text.ParseException;
import java.util.Date;
import java.util.List;

@RestController
@RequestMapping(value = "/form/formMasterApply")
@Api(description = "form", tags = "")
public class FormMasterApplyController extends BaseController {

    @Autowired
    public IFormMasterApplyService formMasterApplyService;

    @Autowired
    public IAttachmentInstService attachmentInstService;

    @Autowired
    private IBpmProcessInstanceService bpmProcessInstanceService;

    @Autowired
    private IUcUserService ucUserService;

    @Autowired
    public IFormViewPubService formViewPubService;


    @Autowired
    private IMdmToolsRealtimeDistributionService realtimeDistributionService;



    //定版属性
    @Autowired
    public IFormAttributePubService formAttributePubService;

    @Autowired
    private IUcDataBaseService ucDataBaseService;

    @Autowired
    public IRealTimeDistributeServer distributeServer;




    @RequestMapping(value = "/save", method = RequestMethod.POST)
    @ApiOperation(value = "保存信息", notes = "保存信息")
    @OperLog(operType = OprLogConstant.ADD, operModul = "", operDescribe = "-保存")
    public void save(@RequestBody FormMasterApplyEntity formMasterApplyEntity) throws ParseException {
        if (BeanUtil.isNotEmpty(formMasterApplyEntity)) {
            injectUpdateDataAuth(formMasterApplyEntity);
        }
        formMasterApplyService.save(formMasterApplyEntity);
    }

    @RequestMapping(value = "/applyAction", method = RequestMethod.GET)
    @ApiOperation(value = "执行分发申请", notes = "执行分发申请")
    public RestResponse applyAction(String id) {
        FormMasterApplyEntity bean = formMasterApplyService.getById(id);
        if(BeanUtil.isNotEmpty(bean)){
            //*********此次做配置校验
            if(StringUtil.isEmpty(bean.getDistributionId())){
                return RestResponse.error("分发任务未配置正确");
            }

            FormViewPubEntity view = formViewPubService.getById(bean.getViewId());

            //查询视图的属性
            FormAttributePubEntity Attribute=new FormAttributePubEntity();
            Attribute.setStatus(SystemConst.NORMAL_STATUS);
            Attribute.setViewId(bean.getViewId());
            List<FormAttributePubEntity>  attributeList =formAttributePubService.getList(Attribute);
            if(BeanUtil.isEmpty(attributeList) || attributeList.size()==0){
                return RestResponse.error("当前视图没有配置属性,请联系维护人员");
            }

            DataBaseEntity dataBaseEntity=ucDataBaseService.queryJdbcById(view.getDatasource());
            DbConfig dbConfig = new DbConfig(dataBaseEntity.getJdbcDrivers(),dataBaseEntity.getJdbcUrl(),dataBaseEntity.getJdbcUser(),
                    dataBaseEntity.getJdbcPassword(),dataBaseEntity.getDbName(),dataBaseEntity.getDbType());


            String sqlStr = getViewDataSql(bean,view,attributeList,dbConfig);

            JdbcSql jdbcSql = new JdbcSql(dbConfig);
            ApplyHandler applyHandler=new ApplyHandler();
            applyHandler.setApplyEntity(bean);
            applyHandler.setView(view);
            applyHandler.setRealTimeDistributeServer(distributeServer);

            //查询出分发配置加入到handler对象中
            RealTimeDistributeConfig realTimeDistributeConfig = realtimeDistributionService.queryDistributionConfigurationById(bean.getDistributionId());
            applyHandler.setRealTimeDistributeConfig(realTimeDistributeConfig);

            jdbcSql.executeStreamQuery(sqlStr,applyHandler);

            //执行完将申请信息改为已处理
            bean.setBizStatus("5");
            formMasterApplyService.save(bean);

        }

        return RestResponse.success();
    }


    public String getViewDataSql(FormMasterApplyEntity bean,FormViewPubEntity view,List<FormAttributePubEntity>  attributeList,DbConfig dbConfig){

        StringBuffer mainSql = new StringBuffer();
        mainSql.append("select ");


        //下标
        int index = 0;
        for (FormAttributePubEntity columnItem : attributeList) {
            index++;
            //data类型数据做时间转字符串;
            if(StringUtil.isNotEmpty(columnItem.getDataType())&& "date".equals(columnItem.getDataType())){
                //根据数据库类型做时间类型转换
                DbTypeEnum dbTypeEnum=dbConfig.getDbTypeEnum();
                if(dbTypeEnum.equals(DbTypeEnum.Oracle)){
                    mainSql.append("TO_CHAR (").append(columnItem.getCode()).append(" , ").append("'yyyy-mm-dd hh24:mi:ss' )").append(" as ").append(columnItem.getCode());
                }else if(dbTypeEnum.equals(DbTypeEnum.Postgresql)){
                    mainSql.append("TO_CHAR (").append(columnItem.getCode()).append(" , ").append("'yyyy-mm-dd hh24:MI:SS' )").append(" as ").append(columnItem.getCode());
                }else if(dbTypeEnum.equals(DbTypeEnum.Oushu)){
                    mainSql.append("TO_CHAR (").append(columnItem.getCode()).append(" , ").append("'yyyy-mm-dd hh24:MI:SS' )").append(" as ").append(columnItem.getCode());
                }else {
                    mainSql.append("DATE_FORMAT (").append(columnItem.getCode()).append(" , ").append("'%Y-%m-%d %H:%i:%s' )").append(" as ").append(columnItem.getCode());
                }

            }else {
                mainSql.append(columnItem.getCode());
            }

            //非最后一个字段用逗号连接
            if (index < attributeList.size()) {
                mainSql.append(", ");
            }
        }
        //拼接表名
        mainSql.append(" from ").append(view.getLinkTable());

        //拼接查询条件
        mainSql.append(" where 1=1 ");
        if(StringUtil.isNotEmpty(bean.getConditionForm())){
            ConditionVo conditionForm=JSON.parseObject(bean.getConditionForm(),ConditionVo.class);
            if(BeanUtil.isNotEmpty(conditionForm)){
                if(StringUtil.isNotEmpty(conditionForm.getConditionType())&&conditionForm.getConditionType().equals("2")){
                    mainSql.append(" and ").append(conditionForm.getConditionDivStr());

                }else if(StringUtil.isNotEmpty(conditionForm.getConditionType())&&conditionForm.getConditionType().equals("1")){
                    if(BeanUtil.isNotEmpty(conditionForm.getConditionList())&&conditionForm.getConditionList().size()>0){
                        for (int i = 0; i <conditionForm.getConditionList().size() ; i++) {
                            ConditionItem item=conditionForm.getConditionList().get(i);
                            mainSql.append(" and ").append(item.getCode()).append(" ").append(item.getType()).append(" '").append(item.getValue()).append("' ");
                        }
                    }

                }
            }
        }
        return mainSql.toString();



    }











    @RequestMapping(value = "/saveBatch", method = RequestMethod.POST)
    @ApiOperation(value = "批量保存信息", notes = "批量保存信息")
    @OperLog(operType = OprLogConstant.UPDATE, operModul = "", operDescribe = "-批量保存修改")
    public void saveBatch(@RequestBody List<FormMasterApplyEntity> list) throws ParseException {
        if (list != null && list.size() > 0) {
            injectUpdateDataAuth(list);
        }
        formMasterApplyService.saveBatch(list);
    }

    @RequestMapping(value = "/deleteById", method = RequestMethod.GET)
    @ApiOperation(value = "根据Id删除数据", notes = "根据Id删除数据")
    @OperLog(operType = OprLogConstant.DELETE, operModul = "", operDescribe = "-删除")
    public void deleteById(String id) {
        if (null != id && !"".equals(id)) {
            FormMasterApplyEntity formMasterApplyEntity = new FormMasterApplyEntity();
            injectUpdateDataAuth(formMasterApplyEntity);
            formMasterApplyEntity.setId(id);
            formMasterApplyService.deleteByEntity(formMasterApplyEntity);
        }
    }

    @RequestMapping(value = "/deleteBatchByIds", method = RequestMethod.POST)
    @ApiOperation(value = "根据Id批量删除数据", notes = "根据Id批量删除数据")
    @OperLog(operType = OprLogConstant.DELETE, operModul = "", operDescribe = "-批量删除")
    public void deleteBatchByIds(@RequestBody List<String> ids) {
        if (null != ids && ids.size() > 0) {
            FormMasterApplyEntity formMasterApplyEntity = new FormMasterApplyEntity();
            injectUpdateDataAuth(formMasterApplyEntity);
            //formMasterApplyService.deleteBatchIds(ids);
            formMasterApplyService.deleteBatchIdsWithPermission(ids, formMasterApplyEntity);
        }
    }

    @RequestMapping(value = "/queryById", method = RequestMethod.GET)
    @ApiOperation(value = "根据Id查询对象", notes = "根据Id查询对象")
    public FormMasterApplyEntity queryById(String id) {
        FormMasterApplyEntity bean = formMasterApplyService.getById(id);
        return bean;
    }

    @RequestMapping(value = "/queryBatchByIds", method = RequestMethod.POST)
    @ApiOperation(value = "根据Id查询对象列表", notes = "根据Id查询对象列表")
    public List queryBatchByIds(@RequestBody List<String> ids) {
        List list = formMasterApplyService.getBatchByIds(ids);
        return list;
    }

    @RequestMapping(value = "/queryPage", method = RequestMethod.GET)
    @ApiOperation(value = "模板分页查询", notes = "模板分页查询")
    public IPage queryPage(FormMasterApplyEntity formMasterApplyEntity, Integer currentPage, Integer pageSize) {
        if (currentPage == null) {
            currentPage = 1;
        }
        if (pageSize == null) {
            pageSize = 10;
        }
        injectCheckDataAuth(formMasterApplyEntity);
        IPage pageBean = formMasterApplyService.formMasterApplyList(formMasterApplyEntity, currentPage, pageSize);
        return pageBean;
    }

    @RequestMapping(value = "/queryList", method = RequestMethod.GET)
    @ApiOperation(value = "模板查询", notes = "模板查询")
    public List queryList(FormMasterApplyEntity formMasterApplyEntity) {
        injectCheckDataAuth(formMasterApplyEntity);
        List list = formMasterApplyService.getList(formMasterApplyEntity);
        return list;
    }

    @RequestMapping(value = "/updateStatus", method = RequestMethod.POST)
    @ApiOperation(value = "修改状态", notes = "修改状态")
    @OperLog(operType = OprLogConstant.UPDATE, operModul = "", operDescribe = "修改")
    public void updateStatus(@RequestBody FormMasterApplyEntity formMasterApplyEntity) throws ParseException {
        formMasterApplyService.updateStatus(formMasterApplyEntity, getUserInfo());
    }

    @RequestMapping(value = "/agreeApproval", method = RequestMethod.POST)
    @ApiOperation(value = "同意申请", notes = "同意申请")
    public RestResponse agreeApproval(String bussinessKey) {
        if (StringUtil.isNotEmpty(bussinessKey)) {
            FormMasterApplyEntity formMasterApplyEntity = formMasterApplyService.getById(bussinessKey);
            if (BeanUtil.isNotEmpty(formMasterApplyEntity)) {
                formMasterApplyEntity.setBizStatus("3");
                formMasterApplyService.updateById(formMasterApplyEntity);
                return RestResponse.success();
            }
        }
        return RestResponse.error();
    }

    @RequestMapping(value = "/refuseApproval", method = RequestMethod.POST)
    @ApiOperation(value = "反对", notes = "反对")
    public RestResponse refuseApproval(String bussinessKey) {
        if (StringUtil.isNotEmpty(bussinessKey)) {
            FormMasterApplyEntity formMasterApplyEntity = formMasterApplyService.getById(bussinessKey);
            if (BeanUtil.isNotEmpty(formMasterApplyEntity)) {
                formMasterApplyEntity.setBizStatus("2");
                formMasterApplyService.updateById(formMasterApplyEntity);
                return RestResponse.success();
            }
        }
        return RestResponse.error();
    }

    @RequestMapping(value = "/getformMasterApplyById", method = RequestMethod.GET)
    @ApiOperation(value = "根据Id查询对象", notes = "根据Id查询对象")
    public FormMasterApplyDTO getformMasterApplyById(String id) {
        FormMasterApplyDTO formMasterApplyDTO = null;
        if(StringUtil.isNotEmpty(id)){
            FormMasterApplyEntity formMasterApplyEntity = formMasterApplyService.getById(id);
            if(BeanUtil.isNotEmpty(formMasterApplyEntity)){
                if(StringUtil.isNotEmpty(formMasterApplyEntity.getApplyUserId())){
                    UcUserEntity ucUserEntity = ucUserService.queryById(formMasterApplyEntity.getApplyUserId());
                    if(BeanUtil.isNotEmpty(ucUserEntity)){
                        formMasterApplyEntity.setApplyUserName(ucUserEntity.getUserName());
                    }
                }
                if(StringUtil.isNotEmpty(formMasterApplyEntity.getApplyUserId())){
                    UcUserEntity ucUserEntity = ucUserService.queryById(formMasterApplyEntity.getApplyUserId());
                    if(BeanUtil.isNotEmpty(ucUserEntity)){
                        formMasterApplyEntity.setApplyUserName(ucUserEntity.getUserName());
                    }
                }
            }
        }
        FormMasterApplyDTO bean = formMasterApplyService.formMasterApplyById(id);
        return bean;
    }






    @RequestMapping(value = "/saveAndInitiate", method = RequestMethod.POST)
    @ApiOperation(value = "保存信息", notes = "保存信息")
    @OperLog(operType = OprLogConstant.ADD, operModul = "", operDescribe = "-保存")
    public RestResponse saveAndInitiate(@RequestBody FormMasterApplyBPMDTO<ProcessCmd> formMasterApplyBPMDTO) throws ParseException {
        BaseUserInfo baseUserInfo = getUserInfo();
        if (BeanUtil.isNotEmpty(formMasterApplyBPMDTO)) {
            FormMasterApplyEntity formMasterApplyEntity = formMasterApplyBPMDTO.getFormMasterApplyEntity();
            if (BeanUtil.isNotEmpty(formMasterApplyEntity)) {

                if (StringUtil.isEmpty(formMasterApplyEntity.getId())) {
                    formMasterApplyEntity.setAppId(baseUserInfo.getAppId());
                    formMasterApplyEntity.setStatus(SystemConst.NORMAL_STATUS);
                    formMasterApplyEntity.setModifyId(baseUserInfo.getUserId());
                    formMasterApplyEntity.setModifyDate(new Date());
                    formMasterApplyEntity.setCreateId(baseUserInfo.getUserId());
                    formMasterApplyEntity.setOrgId(baseUserInfo.getOrgId());
                    formMasterApplyService.save(formMasterApplyEntity);
                    // 发起流程
                    ProcessCmd processCmd = formMasterApplyBPMDTO.getProcessCmd();
                    if (BeanUtil.isNotEmpty(processCmd)) {
                        processCmd.setBusinessKey(formMasterApplyEntity.getId());
                        processCmd.setData(JSON.toJSONString(formMasterApplyEntity));
                        processCmd.setAppId(baseUserInfo.getAppId());
                        bpmProcessInstanceService.startProcessInstance(processCmd);
                    }
                } else {
                    formMasterApplyService.updateById(formMasterApplyEntity);
                    // 推动流程
                    ProcessCmd processCmd = formMasterApplyBPMDTO.getProcessCmd();
                    if (BeanUtil.isNotEmpty(processCmd)) {
                        processCmd.setToEditor(true);
                        processCmd.setData(JSON.toJSONString(formMasterApplyEntity));
                        processCmd.setAppId(baseUserInfo.getAppId());
                        bpmProcessInstanceService.completeSubmitTask(processCmd);
                    }
                }
                // 附件关联业务
                if (StringUtil.isNotEmpty(formMasterApplyEntity.getId())) {
                    List<String> fileIdList = formMasterApplyBPMDTO.getFileIdList();
                    if (fileIdList != null && fileIdList.size() > 0) {
                        attachmentInstService.saveAttInstBizInfo(fileIdList, formMasterApplyEntity.getId(), formMasterApplyEntity.getId());
                    }
                }
                return RestResponse.success();
            }
        }
        return RestResponse.error();
    }
}